package com.bbcare.followup.plat.task;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.SeqUtil;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;

/**
 * @name: 患者窗口期随访提醒短信处理类
 * @author: DemonLee
 * @createTime: 2017.5.27
 * @description: （1）、进入窗口期时给患者发一条短信（随访日期是排班中的一个，但不是今天）;
 *               （2）、窗口期每周发一次；（3）、建议该任务后台每2小时运行一次
 * @modify:
 * 
 */
public class PtWinTaskSmsSendTaskNew implements Job{
    private final Log logger = LogFactory.getLog(PtWinTaskSmsSendTaskNew.class);

    @Autowired
    private IPatientInfoHisService ptHisService;

    @Autowired
    private IPatientService patientSerivce;

    @Autowired
    private IConfCacheDAO confCacheDao;

    @Override
    public void execute(JobExecutionContext context){
        logger.warn("job------start: PtWinTaskSmsSendTaskNew---"+DateUtil.getMillSysDate());

        Map<String, Object> inRule = new HashMap<String, Object>();
        inRule.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
        inRule.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
        inRule.put("ruleType", Constants.FU_INFORM_RULE_SMS_SEND_RULE_TYPE_WIN);// 按窗口期规则发送
        List<Map<String, Object>> outRuleList = null;
        try {
            outRuleList = confCacheDao.listWinQueueFromInformRule(inRule);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return;
        }
        int totalNum = 0;
        if (!CollectionUtils.isEmpty(outRuleList)) {
            int outSize = outRuleList.size();
            int tp = 0;
            float cycleTime = 0;
            String queueId = "";
            String currDateTime = DateUtil.getSysDateA();
            String rangeTime = "";
            String templateType = "";
            String tenantId = "";
            String scheduleFlag ="";
            Map<String, Object> outMap = new HashMap<String, Object>();
            for (tp = 0; tp < outSize; tp++) {
                outMap = outRuleList.get(tp);
                
                String ruleId = (String) outMap.get("id");
                cycleTime = Float.parseFloat("" + outMap.get("cycleTime"));
                queueId = (String) outMap.get("queueId");
                templateType = (String) outMap.get("templateType");
                tenantId = (String) outMap.get("tenantId");
                rangeTime = DateUtil.calcDayByHour(currDateTime, Constants.SUBTRACT_CHAR, cycleTime);
                scheduleFlag = (String) outMap.get("scheduleFlag");
                
                List<PatientTask> epList = new ArrayList<PatientTask>();
                Map<String, Object> paramIn = new HashMap<String, Object>();
                paramIn.put("start", 0);
                paramIn.put("end", 100);// 每次提取100条
                paramIn.put("taskStatus", Constants.PATIENT_TASK_STATUS_INIT);// 未开始的任务
                paramIn.put("currDay", DateUtil.getCurrDate());// 今日在窗口期内
                paramIn.put("templType", Constants.QUESTIONNAIRE_TYPE_0);// 含有门诊问卷
                paramIn.put("revSeqNo", Constants.TASK_SEQ_FOR_INIT);// 去掉建档任务
                paramIn.put("ruleStatus", Constants.TABLE_RECORD_STATUS_NOMAL);// 状态正常的提醒规则
                paramIn.put("nowTime", DateUtil.getSysDate4Hms());// 当前时间是否在允许发送提醒的时间范围内
                paramIn.put("queueId", queueId);// 队列id
                paramIn.put("rangeTime", rangeTime);// 周期内是否已经发送过提醒
                paramIn.put("templateType", templateType);// 模板类型
//                paramIn.put("sendStatus", Constants.PT_INFORM_SMS_STATUS_SUCCESS);// 过滤掉发送状态成功
                //不根据发送状态 过滤 只要发送过就过滤 防止出现 接收结果是失败 实际发送成功 导致循环发送情况
                paramIn.put("opCode", Constants.OP_CODE_3002);
                paramIn.put("opType", Constants.OP_TYPE_BG_ADMIN);
                paramIn.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务
                paramIn.put("tenantId", tenantId);
                
                paramIn.put("ruleId", ruleId);
                String authorId = Constants.BG_LOGIN_NO_ADMIN;// 后台程序处理工号
                String ipAddress = "";
                try {
                    InetAddress netAddress = InetAddress.getLocalHost();
                    ipAddress = netAddress.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    ipAddress = "";
                }

                while (true) {
                    try {
                        /*
                         * 1、今天在窗口期内，但如果今天是窗口期最后一天，则不需要提取出来，因为此时发短信已经来不及了，
                         * 2、需要提取的是含有门诊问卷的任务，若是线上随访任务，则不需要提取，通过app提醒
                         * 3、配置了短信模板的队列才需要发送，未配置则不需要发送
                         */
                        epList.clear();
                        epList = ptHisService.getPatientWindowTaskListNew(paramIn);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return;
                    }

                    if (!CollectionUtils.isEmpty(epList)) {
                        Map<String, Object> dealIn = new HashMap<String, Object>();
                        PatientTask ptVo = new PatientTask();
                        int iep = epList.size();
                        int k = 0;
                        for (k = 0; k < iep; k++) {
                            dealIn.clear();
                            ptVo = epList.get(k);
                            dealIn.put("taskId", ptVo.getId());
                            dealIn.put("userId", ptVo.getUserId());
                            dealIn.put("taskName", ptVo.getTaskName());
                            dealIn.put("ptSchemeId", ptVo.getPtSchemeid());
                            dealIn.put("queueId", ptVo.getQueueId());
                            dealIn.put("authorId", authorId);
                            dealIn.put("updateTime", DateUtil.getTimeString(DateUtil.getSysDateA()));
                            dealIn.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
                            dealIn.put("opCode", Constants.OP_CODE_3002);
                            dealIn.put("opType", Constants.OP_TYPE_BG_ADMIN);
                            dealIn.put("ipAddress", ipAddress);
                            dealIn.put("tenantId", tenantId);
                            dealIn.put("scheduleFlag", scheduleFlag);//是否需要根据排班安排具体随访时间
                            dealIn.put("ruleId", ruleId);//规则ID
                            try {
                            	ptHisService.dealPatientWinTaskSmsSendNew(dealIn);
                                totalNum++;
                            } catch (AppException e) {
                                // TODO Auto-generated catch block
                                logger.error("dealPatientWinTaskSmsSendNew AppException...dealIn==" + dealIn.toString());
                                e.printStackTrace();

                                // 将错误记录存在异常表pt_excp_rd中，后续查询过滤掉这批数据
                                try {
                                    dealIn.put("errMsg", e.getErrMsg());
                                    patientSerivce.savePtExcpInfo(dealIn);
                                } catch (Exception e1) {
                                    // TODO Auto-generated catch block
                                    logger.error("---savePtExcpInfo AppException---dealIn==" + dealIn.toString());
                                    e1.printStackTrace();
                                    // 这里再报错，可能会出现死循环，后续补
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                logger.error("dealPatientWinTaskSmsSendNew Exception...dealIn==" + dealIn.toString());
                                e.printStackTrace();

                                // 将错误记录存在异常表pt_excp_rd中，后续查询过滤掉这批数据
                                try {
                                    dealIn.put("errMsg", "dealPatientWinTaskSmsSendNew Exception:" + e.getMessage());
                                    patientSerivce.savePtExcpInfo(dealIn);
                                } catch (Exception e1) {
                                    // TODO Auto-generated catch block
                                    logger.error("---savePtExcpInfo Exception---dealIn==" + dealIn.toString());
                                    e1.printStackTrace();
                                    // 这里再报错，可能会出现死循环，后续补
                                }
                            }
                        }
                    } else {
                        // 无记录，返回
                        break;
                    }
                }
            }
        }

        logger.warn("---end: dealPatientWinTaskSmsSendNew---total send sms==" + totalNum);

        return;
    }
}
